package com.gitee.maskit.nop.autoconfigure;

import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

@Data
@ConfigurationProperties(prefix = "nop")
public class NopBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    private List<String> patterns = new ArrayList<String>();

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        final NopProvider provider = beanFactory.getBean(NopProvider.class);
        final Environment environment = beanFactory.getBean(Environment.class);
        final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
            beanFactory.getBeanClassLoader());
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();

        int index = 0;
        String pattern;
        while (null != (pattern = environment.getProperty("nop.patterns[" + (index++) + "]"))) {
            try {
                Resource[] resources = resolver.getResources(pattern);
                for (Resource resource : resources) {
                    Class type = ClassUtils.forName(metadataReaderFactory.getMetadataReader(resource)
                        .getClassMetadata().getClassName(), null);
                    if (type.isInterface()) {
                        final String[] names = beanFactory.getBeanNamesForType(type,
                            true, false);
                        if (names.length <= 0) {
                            beanFactory.registerSingleton("NOP-" + type.getName(),
                                Proxy.newProxyInstance(
                                    Thread.currentThread().getContextClassLoader(),
                                    new Class[]{type},
                                    new NopInvocationHandler(provider)));
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
